import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) { this.val = val; }
}

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> back = new LinkedList<>();

        if (root == null) {
            return back;
        }

        //存储二叉树的队列
        Queue<TreeNode> queue = new LinkedList<>();
        //入队
        queue.offer(root);

        while (!queue.isEmpty()) {
            //记录每一行数据
            List<Integer> level = new ArrayList<>();
            //每一行数据个数
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                //实际上因为录入数据时已判断为非空，此处不可能为空
                level.add(node.val);

                //录入下一行数据
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }

            //把最新的一行放前面
            back.add(0, level);
        }

        return back;
    }

    public static void main(String[] args) {
        // 构建测试用的二叉树 [3,9,20,null,null,15,7]
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        Solution solution = new Solution();
        List<List<Integer>> result = solution.levelOrderBottom(root);

        // 输出结果
        System.out.println("层序遍历自底向上的结果:");
        for (List<Integer> level : result) {
            System.out.println(level);
        }
    }
}